<?php
namespace app\admin\controller\market;

/**
 * 商品控制器
 */

use app\common\controller\AdminController;

use think\facade\Session;
use think\facade\View;
use think\facade\Db;
use think\app;

class Seckill extends AdminController
{
    public function initialize()
    {
        parent::initialize();
        $this->model = app('app\common\model\market\MarketItem');
        $this->Item = app('app\common\model\mall\Item');
        $this->ItemSku = app('app\common\model\mall\ItemSku');
        $this->MarketItemSku = app('app\common\model\market\MarketItemSku');
        $this->ItemSkuSpec = app('app\common\model\mall\ItemSkuSpec');
        $this->ItemSpec = app('app\common\model\mall\ItemSpec');
        $this->ItemSpecValue = app('app\common\model\mall\ItemSpecValue');
        $this->ItemCategory = app('app\common\model\common\Categories');
        $this->SeckillTime = app('app\common\model\market\SeckillTime');
    }

    /**
     * 秒杀商品审核列表
     * @return View
     */
    public function check_index()
    {
        //平台审核需获取所有商家数据，故传type值区分，屏蔽store_id判断
        $type = 1;
        View::assign('type', $type);
        return view('index');
    }
    /**
     * 获取附带数据
     * @param Request $request
     * @return mixed
     */
    public function otherData($request)
    {
        $otherData = $this->SeckillTime->select();
        $type = 0;
        View::assign('type', $type);
        View::assign('otherData',$otherData);
    }

    /**
     * 审核秒杀商品
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|mixed|\think\response\Json|\think\response\View
     */
    public function check()
    {
        if ($this->request->isPost()) { //更新操作

            $data = $this->request->only(['id','comment','status']);

            $info = $this->model->find($data['id']);

            try {
                Db::startTrans();

                Db::name('market_item')->where('id',$data['id'])->save($data);
                //$goods = $info->save($data);


                Db::commit();

                return json(['code' => 1, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '更新失败' . $e->getMessage()]);


            }
        } else {//页面数据回显


            $data['id'] = $this->request->param('id');

            $info = $this->model->with(['ItemSku', 'ItemSkuSpec' => function ($query) {
                $query->with('ItemSpec')->group('spec_id')->select();
            },'SeckillTime'])->find($data['id'])->toArray();

            //dd($info['SeckillTime'][0]['pivot']['time_id']);

            //分类
            $categories = $this->ItemCategory->with('allChilds')->where('parent_id', 0)->select();
            //sku
            $sku = $this->ItemSpec->with('spec_value')->select();
            //规格名
            if ($info['spec_type'] == 2) {
                foreach (explode('_', $info['ItemSku'][0]['spec_sku_id']) as $k => $v) {
                    $list[] = $this->ItemSpecValue->where('spec_value_id', $v)->with('category')->select()->toArray();
                }


                //sku
                //$sku = $this->ItemSpec->with('spec_value')->get();

                $spec = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_id');

                $spec_value = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_value_id');


                $item_spec_value = $this->ItemSpecValue->column('*', 'spec_value_id');


                //获取sku组合
                foreach ($info['ItemSku'] as $key => $value) {

                    foreach (explode('_', $value['spec_sku_id']) as $k => $v) {

                        $info['ItemSku'][$key]['spec'][$k] = $item_spec_value[$v]['spec_value'];
                    }
                }

                //判断是否存在规格中
                foreach ($sku as $key => $value) {

                    if (in_array($value->spec_id, $spec)) {
                        $value->active = 'sku-active';
                    } else {
                        $value->active = ' ';
                    }
                    foreach ($value->spec_value as $k => $v) {

                        if (in_array($v->spec_value_id, $spec_value)) {
                            $value->spec_value[$k]['active'] = 'sku-active';
                        } else {
                            $value->spec_value[$k]['active'] = ' ';
                        }
                    }
                }
                $otherData = $this->SeckillTime->select();

                return view('check', compact('info', 'categories', 'sku', 'list','otherData'));

            }
            return view('check', compact('info', 'categories', 'sku','otherData'));

        }
    }

    /**
     * 条件查询
     * @param array $arr
     * @return array
     */
    public function get_where($arr = [])
    {
        $array = [];

        $admin = Session::get('admin');
        @$arr['type'] != 1 && $array[] = ['store_id', '=', $admin['store_id']];
        if (isset($arr['goods_name']) && !empty($arr['goods_name'])) {
            $array[] = ['market_title', 'like', '%' . $arr['goods_name'] . '%'];
        }

        isset($arr['status']) && !empty($arr['status']) && $array[] = ['status', '=', $arr['status']];


        return $array;
    }
    /**
     * 关联模型
     * @return array
     */
    public function get_with()
    {
        return ['store'];
    }

    /**
     * 获取验证规则
     * @param $post
     * @return array
     */
    public function get_check_rule($post)
    {

        $rule = [
            'market_title|商品标题' => 'require|unique:market_item,market_title,' . $post['id'] . ',id',
            'thumb|活动主图' => 'require',
            'image|活动轮播图' => 'require',
            'content|活动详情内容' => 'require',
            'spec|规格' => 'require',

        ];

        return $rule;
    }

    /**
     * 添加商品
     * @param ArticleRequest $this ->request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function add()
    {
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $post = $this->request->only(['market_title','store_id','time_id', 'id', 'item_id','thumb', 'image', 'spec', 'content']);
                $rule = [];
                if (method_exists($this, 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }

                $this->validate($post, $rule);

                $post['app_id'] = $this->model->getApp();
                $post['store_id'] = $this->model->get_store();
                //商品主表获取总库存和最低单价
                $post['inventory'] = array_sum(array_column($post['spec'],'inventory'));
                $post['market_price'] = min(array_column($post['spec'],'market_price'));
                $post['goods_price'] = min(array_column($post['spec'],'goods_price'));

                $this->model->save($post); //商品数据入库

                $skuData = $post['spec'];//多规格数据

                foreach ($skuData as $key => $value) {
                    $skuData[$key]['market_id'] = $this->model->id;
                    $skuData[$key]['app_id'] = $this->model->getApp();
                    //从普通商品扣除库存到活动中
                   // if (!$this->ItemSku->where('id',$value['sku_id'])->dec('inventory',$value['inventory'])->update()) throw new \Exception("库存不足");

                }
                //sku添加
                $this->MarketItemSku->saveAll($skuData);

                Db::commit();
                return json(['code' => 1, 'msg' => '新增成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '新增失败' . $e->getMessage()]);

            }
        } else {
            //分类
            $categories = $this->ItemCategory->with('allChilds')->where(['parent_id' => 0, 'type' => 3])->select();

            //sku
            $sku = $this->ItemSpec->with('SpecValue')->select();
            $otherData = $this->SeckillTime->select();

            return view('edit', compact('categories', 'sku','otherData'));
        }
    }

    /**
     * 选择商品
     * @return View
     */
    public function choice()
    {
        return view('');
    }

    /**
     * 营销活动选择商品
     * @return \think\response\Json
     */
    public function choice_item()
    {

        $data['id'] = $this->request->param('id');

        $info = $this->Item->with(['ItemSku', 'ItemSkuSpec' => function ($query) {
            $query->with('ItemSpec')->group('spec_id')->select();
        }])->find($data['id'])->toArray();

        //分类
        $categories = $this->ItemCategory->with('allChilds')->where('parent_id', 0)->select();
        //sku
        $sku = $this->ItemSpec->with('spec_value')->select();
        //规格名
        if ($info['spec_type'] == 2) {
            foreach (explode('_', $info['ItemSku'][0]['spec_sku_id']) as $k => $v) {
                $list[] = $this->ItemSpecValue->where('spec_value_id', $v)->with('category')->select()->toArray();
            }


            //sku
            //$sku = $this->ItemSpec->with('spec_value')->get();

            $spec = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_id');

            $spec_value = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_value_id');


            $item_spec_value = $this->ItemSpecValue->column('*', 'spec_value_id');


            //获取sku组合
            foreach ($info['ItemSku'] as $key => $value) {

                foreach (explode('_', $value['spec_sku_id']) as $k => $v) {

                    $info['ItemSku'][$key]['spec'][$k] = $item_spec_value[$v]['spec_value'];
                }
            }

            //判断是否存在规格中
            foreach ($sku as $key => $value) {

                if (in_array($value->spec_id, $spec)) {
                    $value->active = 'sku-active';
                } else {
                    $value->active = ' ';
                }
                foreach ($value->spec_value as $k => $v) {

                    if (in_array($v->spec_value_id, $spec_value)) {
                        $value->spec_value[$k]['active'] = 'sku-active';
                    } else {
                        $value->spec_value[$k]['active'] = ' ';
                    }
                }
            }




        }
        $data = compact('info', 'categories', 'sku', 'list');
        return json(['code' => 200, 'data' => $data]);
    }
    /**
     * 更新商品
     * @param $data ['id']
     * @return \Illuminate\Contracts\View\View
     */
    public function edit()
    {
        if ($this->request->isPost()) { //更新操作

            $data = $this->request->only(['market_title', 'time_id','id', 'store_id','item_id','thumb', 'image', 'spec', 'content']);

            $info = $this->model->find($data['id']);

            try {
                Db::startTrans();

                if (method_exists($this, 'get_check_rule')) {
                    $rule = $this->get_check_rule($data ?? []);
                    $this->validate($data, $rule);
                }
                //商品主表获取总库存和最低单价
                $data['inventory'] = array_sum(array_column($data['spec'],'inventory'));
                $data['market_price'] = min(array_column($data['spec'],'market_price'));

                $data['status'] =0;
                $goods = $info->save($data);
                $skuData = $data['spec'];//多规格数据
                //删除之前存在的
                //删除所有废弃的规格值
                $no_spec_list = $this->MarketItemSku->where('market_id', $data['id'])->select();
                $no_spec_list && $no_spec_list->delete();

                foreach ($skuData as $key => $value) {
                    $skuData[$key]['market_id'] = $data['id'];
                    $skuData[$key]['app_id'] = $this->model->getApp();
                    //从普通商品扣除库存到活动中
                    // if (!$this->ItemSku->where('id',$value['sku_id'])->dec('inventory',$value['inventory'])->update()) throw new \Exception("库存不足");

                }

                $this->MarketItemSku->saveAll($skuData);

                Db::commit();

                return json(['code' => 1, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '更新失败' . $e->getMessage()]);


            }
        } else {//页面数据回显


            $data['id'] = $this->request->param('id');

            $info = $this->model->with(['ItemSku', 'ItemSkuSpec' => function ($query) {
                $query->with('ItemSpec')->group('spec_id')->select();
            },'SeckillTime'])->find($data['id'])->toArray();

            //dd($info['SeckillTime'][0]['pivot']['time_id']);

            //分类
            $categories = $this->ItemCategory->with('allChilds')->where('parent_id', 0)->select();
            //sku
            $sku = $this->ItemSpec->with('spec_value')->select();
            //规格名
            if ($info['spec_type'] == 2) {
                foreach (explode('_', $info['ItemSku'][0]['spec_sku_id']) as $k => $v) {
                    $list[] = $this->ItemSpecValue->where('spec_value_id', $v)->with('category')->select()->toArray();
                }


                //sku
                //$sku = $this->ItemSpec->with('spec_value')->get();

                $spec = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_id');

                $spec_value = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_value_id');


                $item_spec_value = $this->ItemSpecValue->column('*', 'spec_value_id');


                //获取sku组合
                foreach ($info['ItemSku'] as $key => $value) {

                    foreach (explode('_', $value['spec_sku_id']) as $k => $v) {

                        $info['ItemSku'][$key]['spec'][$k] = $item_spec_value[$v]['spec_value'];
                    }
                }

                //判断是否存在规格中
                foreach ($sku as $key => $value) {

                    if (in_array($value->spec_id, $spec)) {
                        $value->active = 'sku-active';
                    } else {
                        $value->active = ' ';
                    }
                    foreach ($value->spec_value as $k => $v) {

                        if (in_array($v->spec_value_id, $spec_value)) {
                            $value->spec_value[$k]['active'] = 'sku-active';
                        } else {
                            $value->spec_value[$k]['active'] = ' ';
                        }
                    }
                }
                $otherData = $this->SeckillTime->select();

                return view('edit', compact('info', 'categories', 'sku', 'list','otherData'));

            }
            return view('edit', compact('info', 'categories', 'sku','otherData'));

        }


    }


    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy()
    {
        $ids = $this->request->param('ids');
        if (!is_array($ids) || empty($ids)){
            return json(['code'=>1,'msg'=>'请选择删除项']);
        }

        try{
            $items = $this->model->destroy($ids);
            $skus = $this->ItemSku->whereIn('goods_id',$ids)->select();
            $skus->delete();
            $sku_spec = $this->ItemSkuSpec->whereIn('goods_id',$ids)->select();
            $sku_spec->delete();
            return json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            return json(['code'=>1,'msg'=>'删除失败']);
        }
    }
    /**
     * 单个字段操作
     * @return \think\response\Json
     */
    public function action()
    {

        $param = $this->request->param();

        try {
            $row = $this->model->where('id', $param['id'])->find();

            $row->save($param);

        } catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => $exception->getMessage()]);
        }
        return json(['code' => 0, 'msg' => '操作成功']);
    }
}